package logic

import (
	"cartsrv/models/mysql"
	"cartsrv/models/redisinit"
	"context"
	"fmt"

	"cartsrv/cartsrv"
	"cartsrv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cartsrv.CartAddRequest) (*cartsrv.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	goods := mysql.Goods{}
	err := goods.GoodsInfo(int(in.GoodsId))
	if err != nil {
		logx.Error("商品不存在")
		return nil, fmt.Errorf("商品不存在")
	}
	if goods.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	if goods.GoodsNumber < in.Number {
		logx.Error("库存不足")
		return nil, fmt.Errorf("库存不足")
	}
	redisinit.CartAdd(int(in.UserId), int(in.GoodsId), int(in.Number), goods.GoodsStyle,
		goods.GoodsTitle, goods.GoodsCover, goods.Price)
	return &cartsrv.CartAddResponse{}, nil
}
